const jwt = require("jsonwebtoken");
const { createUser } = require("../service/userService");
const { userRegisterError } = require("../constant/error");
const { JWT_SECRET } = require("../config/default");
const { getUserInfo, updateById } = require("../service/userService");
class UserController {
  async register(ctx, next) {
    const { user_name, password } = ctx.request.body;
    // console.log(ctx.request.body);

    // 传递参数到 createUser 函数
    const res = await createUser(user_name, password);
    // console.log(res);
    try {
      ctx.body = {
        code: 0,
        msg: "用户注册成功",
        result: {
          id: res.id,
          user_name: res.user_name,
        },
      };
    } catch (err) {
      ctx.app.emit("error", userRegisterError, err);
    }
  }
  async login(ctx, next) {
    const { user_name } = ctx.request.body;
    try {
      // 剔除password
      const { password, ...res } = await getUserInfo({ user_name });
      ctx.body = {
        code: 0,
        msg: "用户登录成功",
        result: {
          token: jwt.sign(res, JWT_SECRET, { expiresIn: "1d" }),
          user: res,
        },
      };
    } catch (err) {
      console.error(err, "登录失败");
    }
  }
  async changePassword(ctx, next) {
    const id = ctx.state.user.id;
    const password = ctx.request.body.password;
    if (await updateById({ id, password })) {
      ctx.body = {
        code: 0,
        msg: "修改密码成功",
        result: "",
      };
    } else {
      ctx.body = {
        code: "10007",
        message: "修改密码失败",
        result: "",
      };
    }
  }
}
module.exports = new UserController();
